package com.d.main;

import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.IIOException;
import javax.imageio.ImageIO;

public class ImageOperate {

	/**
	 * 修改图片大小
	 */
	public static void alterSize(String srcImgFile, int maxWidth) {

		// System.out.print("文件路径为:"+"//"+srcImgFile);
		//String fileName = "D:\\eclipseWS\\WebHarvest\\output\\output\\3.jpg";
		String fileName = srcImgFile;
		String root = "";
		java.io.File file = new java.io.File(fileName);
		if (file.exists())
			System.out.println("文件存在");
		else
			System.out.println("文件不存在");


		BufferedImage src = null;
		try {
			src = javax.imageio.ImageIO.read(file);
			int srcWidth = src.getWidth();
			int srcHeight = src.getHeight();
			System.out.println("srcWidth/srcHeigh = "+srcWidth+"/"+srcHeight);
			//int max = srcWidth>srcHeight?srcWidth:srcHeight;
			
			int new_w = 0, new_h = 0;
			if(srcWidth>maxWidth){
				new_w = srcWidth*maxWidth/srcWidth;
				new_h = srcHeight*maxWidth/srcWidth;
			}else{
				new_w = srcWidth;
				new_h = srcHeight;
			}
			System.out.println("new_w/new_h = "+new_w+"/"+new_h);
			java.awt.image.BufferedImage tag = new java.awt.image.BufferedImage(
					new_w, new_h, java.awt.image.BufferedImage.TYPE_INT_RGB);
			tag.getGraphics().drawImage(src, 0, 0, new_w, new_h, null);
			
			String imgFormat = srcImgFile.substring(srcImgFile.lastIndexOf(".")+1);
			
			ImageIO.write(tag, imgFormat, new File(srcImgFile));
			
	

		} catch (IIOException ee) {
			ee.printStackTrace();
			System.out.print("这里出错了");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}// End sizeAlter

	public static void main(String[] arg){
		ImageOperate.alterSize("D:\\eclipseWS\\WebHarvest\\output\\output\\3.jpg",400);
	}
}
